package org.javason.jsonrpc.impl;

import static org.javason.jsonrpc.JsonRpcConstants.ID;
import static org.javason.jsonrpc.JsonRpcConstants.PARAMS;
import static org.javason.jsonrpc.JsonRpcConstants.METHOD;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import net.sf.json.JSONException;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;

import org.javason.json.BeanToJsonSerializer;
import org.javason.jsonrpc.JsonRpcMessageContext;
import org.javason.util.Debug;
import org.javason.util.HttpServletRequestUtils;

public class JsonRpcInvocationRequestFactory {
	public static final String VERSION = "$Rev: 50408 $";
	private static final Logger LOG = Logger.getLogger(JsonRpcInvocationRequestFactory.class);
	private JsonRpcInvocationRequestFactory() {}
	
	public static JsonRpcInvocationRequest createPostRequest(JsonRpcService service, HttpServletRequest request) throws UnsupportedEncodingException, IOException {
		int length = request.getContentLength();
		String inputString = HttpServletRequestUtils.getRequestContent(request);
		Debug.log(LOG, "recieved(%s): %s", length, inputString);
		assert (inputString.length() == length);
		
		JsonRpcInvocationRequest serviceReq = new JsonRpcInvocationRequest(inputString);
		
		JsonRpcMessageContext msgCtx = new JsonRpcMessageContextImpl(
				service.getServiceClass().getSimpleName(), request);
		
		serviceReq.setMessageContext(msgCtx);
		return serviceReq;
	}

	public static JsonRpcInvocationRequest createPostRequest(JsonRpcService service, String request) throws UnsupportedEncodingException, IOException {
		Debug.log(LOG, "recieved(%s): %s", request.length(), request);
		JsonRpcInvocationRequest serviceReq = new JsonRpcInvocationRequest(request);
		
		serviceReq.setMessageContext(null);
		return serviceReq;
	}
	
	public static JsonRpcInvocationRequest createGetRequest(JsonRpcService service, HttpServletRequest request) throws JSONException {
		String reqPathInfo = request.getPathInfo();
		List<String> pathInfo = HttpServletRequestUtils.splitPath(reqPathInfo);
		String methodName = HttpServletRequestUtils.getMethodName("", pathInfo);
		
		JSONObject jsonParams = (JSONObject) BeanToJsonSerializer.serialize(HttpServletRequestUtils.getParams(request));
		JSONObject jsonRequest = new JSONObject();
		jsonRequest.put(ID, JSONNull.getInstance());
		jsonRequest.put(PARAMS, jsonParams);
		jsonRequest.put(METHOD, methodName);
		
		JsonRpcInvocationRequest serviceReq = new JsonRpcInvocationRequest(jsonRequest);
		
		JsonRpcMessageContext msgCtx = new JsonRpcMessageContextImpl(
				service.getServiceClass().getSimpleName(), request);
		
		serviceReq.setMessageContext(msgCtx);
		return serviceReq;
	}
}
